import React from "react";
import { useState, useEffect } from 'react';
import { CRow, CTable, CTableBody, CTableDataCell, CTableHead, CTableHeaderCell, CTableRow, CPagination, CPaginationItem } from '@coreui/react';
import { useSelector } from 'react-redux'


const ListOfDoctors = () => {
  const [doctorsInfo, setDoctorsInfo ] = useState([]);
  const [params, setParams] = useState({
    schedule_name: 'schedule',
    doctors_name: null,
    limit: 15,
    offset: 0,
    });
  const token = useSelector((state) => state.token);


  const nextPage = () => {
    setParams(prevParams => ({
    ...prevParams,
      offset: prevParams.offset + params.limit,
    }));
    fetchDoctorsInfo();
  };


  const previousPage = () => {
    if (params.offset > 0) {
      setParams(prevParams => ({
      ...prevParams,
        offset: prevParams.offset - params.limit,
      }));
      fetchDoctorsInfo();
    }
  };

  const fetchDoctorsInfo = async () => {
    try {
        const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/doctors/doctors_info?limit=${params.limit}&offset=${params.offset}`,
          {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
          }
        );
        const data = await response.json();
        setDoctorsInfo(data);
    } catch (error) {
        console.error('Ошибка при получении данных:', error);
    }
    };
  

  useEffect(() => {
      fetchDoctorsInfo();
      }, [params]);

  const columns = [
    { key: 'name', _style: { width: '30%' }, label: 'ФИО' },
    { key: 'modality', _style: { width: '20%' }, label: 'Модальность' },
    { key: 'additional_modality', _style: { width: '15%' }, label: 'Дополнительная модальность' },
  ];

    return (
      <>
        <h1>Состав специалистов</h1>
        <br></br>
        <br></br>
        <CRow>
          <CTable striped>
            <CTableHead>
              <CTableRow>
                {columns.map((column, index) => (
                  <CTableHeaderCell key={index} scope="col">{column.label}</CTableHeaderCell>
                ))}
              </CTableRow>
            </CTableHead>
            <CTableBody>
              {doctorsInfo.map((item, index) => (
                <CTableRow key={index}>
                  <CTableDataCell>{item.name}</CTableDataCell>
                  <CTableDataCell>{item.modality}</CTableDataCell>
                  <CTableDataCell>
                    {item.additional_modality && 
                      item.additional_modality.map((modality, index) => (
                        <span key={index}>{modality}, </span>
                      ))
                    }
                  </CTableDataCell>
                </CTableRow>
              ))}

            </CTableBody>
          </CTable>
        </CRow>
          <CPagination align="end" aria-label="Page navigation example">
          <CPaginationItem onClick={previousPage}>Previous</CPaginationItem>
          <CPaginationItem onClick={nextPage}>Next</CPaginationItem>
        </CPagination>
      </>
    )
}

export default ListOfDoctors